/** 
  学生成绩维护
*/
<template>
  <div class="score-change-apply-container">
    <!-- 成绩变更申请列表页开始 -->
    <div v-if="indexKey === 0">
      <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
        <el-row :gutter="24" style="height: 50px;">
          <!-- 学年学期 -->
          <el-col :span="8">
            <el-form-item :label="$t('scoreEntrySwitch.semester')">
              <calendar-select ref="semester" v-model="queryForm.condition.calendarId" @load-done="calendarIdLoadDone" :placeholder="$t('common.pla.pleaseSelect')"></calendar-select>
            </el-form-item>
          </el-col>
          <!-- 课程代码/名称 -->
          <el-col :span="8">
            <el-form-item :label="$t('courseScoreMana.teachingClassCode')">
              <el-select
                v-model.trim="queryForm.condition.course"
                :remote-method="remoteMethod"
                filterable
                remote
                clearable
                :placeholder="$t('common.pla.pleaseInput')"
                style="width:100%">
                <el-option
                  v-for="item in options.courseCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card
        v-loading="loading"
        shadow="never"
        body-style="padding: 24px;"
        style="margin-top:24px">
        <h1 class="condition-title">{{ $t('scoreChangeApply.studentList') }}</h1>
        <div class="div-main clearfix">
          <div class="float-left" style="margin-bottom: 20px;">
            <el-input
              clearable
              v-model="queryForm.condition.studentIdOrName"
              :placeholder="$t('scoreChangeApply.studentSearchText')"
              style="width:250px"
              @change="onSubmit"
              @keyup.enter.native="onSubmit">
                <i slot="prefix"
                  class="el-icon-search"
                  style="margin-top:10px;cursor:pointer"
                  @click="onSubmit">
                </i>
            </el-input>
          </div>
          <div class="float-right">
            <!-- 删除成绩 -->
            <el-button type="danger" @click="deleteScore()">{{ $t('studentScoreMaintain.deleteScore') }}</el-button>
            <!-- 导出 -->
            <el-button @click="exportScore()">{{ $t('scoreMangementBase.export') }}</el-button>
          </div>
        </div>
        <edu-table :pagination="false" :order='true' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <!-- 学号 -->
          <edu-table-column :label="$t('scoreMangementBase.studentId')" prop="studentId">
            <template slot-scope="scope">
              <!-- 查看学生基本信息 -->
              <el-button type="text" @click="selectStudentInfo(scope.row)">{{ scope.row.studentId }}</el-button>
            </template>
          </edu-table-column>
          <!-- 姓名 -->
          <edu-table-column :label="$t('scoreMangementBase.studentName')" prop="studentName"></edu-table-column>
          <!-- 课程代码 -->
          <edu-table-column :label="$t('scoreEntryMana.courseCode')" prop="courseCode"></edu-table-column>
          <!-- 课程名称 -->
          <edu-table-column :label="$t('scoreEntryMana.courseName')" prop="courseName"></edu-table-column>
          <!-- 课程序号 -->
          <edu-table-column :label="$t('scoreEntryMana.courseNum')" prop="courseNum"></edu-table-column>
          <!-- 课程类别 -->
          <edu-table-column :label="$t('scoreEntryMana.courseType')" prop="courseLabel"></edu-table-column>
          <!-- 成绩 -->
          <edu-table-column :label="$t('scoreMangementBase.grade')" prop="scoreValue"></edu-table-column>
          <!-- 学分 -->
          <edu-table-column :label="$t('scoreEntryMana.credit')" prop="credit"></edu-table-column>
          <!-- 绩点 -->
          <edu-table-column :label="$t('gradeRelatedSetting.gradePoint')" prop="gradePoint"></edu-table-column>
          <!-- 录入人 -->
          <edu-table-column :label="$t('courseScoreMana.entryPerson')" prop="importUser"></edu-table-column>
          <!-- 录入时间 -->
          <edu-table-column :label="$t('scoreEntryMana.entryTime')" prop="importTime"></edu-table-column>
          <!-- 操作 -->
          <edu-table-column :label="$t('common.text.operation')" prop="operation" fit>
            <template slot-scope="scope">
              <!-- 查看 -->
              <el-button type="text" @click="selectInfo(scope.row)">{{ $t('scoreMangementBase.select') }}</el-button>
              <!-- 修改 -->
              <el-button type="text" @click="editInfo(scope.row)">{{ $t('scoreMangementBase.change') }}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 成绩变更申请列表页结束 -->
    <!-- 学生基本信息开始 -->
    <div v-if="indexKey === 1">
      <student-basic-info :detailInfo="detailInfo" @refresh-main-page="refreshMainPage"></student-basic-info>
    </div>
    <!-- 学生基本信息结束 -->
    <!-- 课程成绩信息开始 -->
    <div v-if="indexKey === 2">
      <course-grade-info :detailInfo="detailInfo" @refresh-main-page="refreshMainPage"></course-grade-info>
    </div>
    <!-- 课程成绩信息结束 -->
    <!-- 编辑课程成绩信息开始 -->
    <div v-if="indexKey === 3">
      <course-grade-info-edit :detailInfo="detailInfo" @refresh-main-page="refreshMainPage"></course-grade-info-edit>
    </div>
    <!-- 编辑课程成绩信息结束 -->
    <!-- 删除成绩弹框 -->
    <el-dialog
      ref="deleteDialog"
      :before-close="beforeClose"
      :title="title"
      width="30%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogForm" label-position="right" ref="dialogForm" label-width="90px" style="padding-right: 30px;">
        <el-row>
          <el-col :span="24" style="color: red;">
            <!-- 删除 -->
            <el-form-item
              :label="$t('scoreMangementBase.attention') + '：'"
              prop="deleteReason">
              {{ $t('scoreMangementBase.deleteGradeTip') }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!-- 删除原因 -->
            <el-form-item
              :label="$t('scoreMangementBase.deleteReason') + '：'"
              prop="deleteReason"
              :rules="[{ required: true, message: $t('scoreMangementBase.requireDeleteTip'), trigger: 'blur' },{ validator: checkSpecial, trigger: 'blur'}]">
              <el-input type="textarea" :rows="5" :placeholder="$t('common.pla.pleaseInput')" v-model="dialogForm.deleteReason" :maxlength="32" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <template>
          <el-button @click="cancel('dialogForm')">{{ $t('common.btn.cancel') }}</el-button>
          <el-button type="primary" @click="confirm('dialogForm')">{{ $t('common.btn.confirm') }}</el-button>
        </template>
      </span>
    </el-dialog>
    <edu-export-dialog
      :disabled="exportButton"
      :title="$t('message.prompt')"
      ref="downloadRef"
      :data="exportResult">
    </edu-export-dialog>
    <!-- 短信验证弹框 -->
    <el-dialog
      :before-close="beforeCloseMsg"
      :title="titleMsg"
      width="70%"
      :visible.sync="dialogVisibleMsg"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogFormMsg" label-position="right" ref="dialogFormMsg" label-width="120px">
        <el-row>
          <el-col :span="16">
            <!-- 短信验证码 -->
            <el-form-item
              :label="$t('scoreEntryMana.verificationCode') + '：'"
              prop="verificationCode"
              :rules="[{ required: true, message: $t('scoreEntryMana.requireVerificationCode'), trigger: 'blur' },{ validator: validateMessage, trigger: 'blur'}]">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="dialogFormMsg.verificationCode" :maxlength="6" clearable style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 密码序号 -->
            <el-form-item :label="$t('scoreEntryMana.passwordNum') + '：'">{{ passwordNum }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelMsg('dialogFormMsg')">{{ $t('common.btn.cancel') }}</el-button>
        <el-button type="primary" @click="confirmMsg('dialogFormMsg')">{{ $t('common.btn.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import baseUrl from 'common/src/api/scoreManagement/env';
import scoreManagementApi from 'common/src/api/scoreManagement/scoreManagement';
import { queryDic } from 'common/src/api/dictionary';
import { coursesLabelList } from 'common/src/api/score/courseScoreChangeMange.js';
import studentBasicInfo from './studentBasicInfo';
import courseGradeInfo from './courseGradeInfo';
import courseGradeInfoEdit from './courseGradeInfoEdit';
export default {
  components: {
    'student-basic-info': studentBasicInfo,
    'course-grade-info': courseGradeInfo,
    'course-grade-info-edit': courseGradeInfoEdit
  },
  data () {
    return {
      operationStatus: '',
      messageInfo: {},
      passwordNum: '05',
      dialogFormMsg: {
        verificationCode: ''
      },
      dialogVisibleMsg: false,
      titleMsg: '',
      auths: [],
      userInfo: {},
      indexKey: 0,
      dataList: [],
      detailInfo: {},
      multipleSelection: [],
      queryForm: {
        condition: {
          calendarId: '',
          course: '',
          studentIdOrName: ''
        },
        pageNum_: 1,
        pageSize_: 20,
        total_: 0
      },
      options: {
        courseCodeList: [],
        courseType: [],
        auditStatusOption: [
          {
            value: 0,
            label: '草稿'
          },
          {
            value: 1,
            label: '审批中'
          },
          {
            value: 2,
            label: '驳回'
          },
          {
            value: 3,
            label: '审核通过'
          }
        ]
      },
      title: '',
      dialogVisible: false,
      dialogForm: {
        deleteReason: ''
      },
      exportButton: false,
      exportResult: null
    }
    
  },
  props: {

  },
  created() {

  },
  mounted() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
      if (JSON.parse(localStorage.getItem("sessiondata")).mockUser) {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).mockUser
      } else {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).user
      }
    }
    if (this.queryForm.condition.calendarId) {
      this.onSubmit()
    }
    this.getCourseType()
  },
  methods: {
    confirmMsg(dialogFormMsg) {
      if (this.operationStatus === 'del') {
        this.$refs[dialogFormMsg].validate(valid => {
          if (valid) {
            scoreManagementApi.validateMessage({
              "id": this.messageInfo.id,
              "code": this.dialogFormMsg.verificationCode,
              "receiverCode": this.messageInfo.receiverCode
            }).then(res => {
              if (res.code === 200) {
                this.dialogFormMsg.verificationCode = ''
                this.$refs[dialogFormMsg].clearValidate()
                this.dialogVisibleMsg = false
                let deleteArray = this.multipleSelection.map(value => {
                  return value.id
                })
                this.title = this.$t('scoreMangementBase.deleteGrade')
                this.dialogVisible = true
              }
            })
          }
        })
      } else if (this.operationStatus === 'edit') {
        this.$refs[dialogFormMsg].validate(valid => {
          if (valid) {
            scoreManagementApi.validateMessage({
              "id": this.messageInfo.id,
              "code": this.dialogFormMsg.verificationCode,
              "receiverCode": this.messageInfo.receiverCode
            }).then(res => {
              if (res.code === 200) {
                this.dialogFormMsg.verificationCode = ''
                this.$refs[dialogFormMsg].clearValidate()
                this.dialogVisibleMsg = false
                this.indexKey = 3
              }
            })
          }
        })
      }
    },
    cancelMsg(dialogFormMsg) {
      this.operationStatus = ''
      this.dialogFormMsg.verificationCode = ''
      this.$refs[dialogFormMsg].clearValidate()
      this.dialogVisibleMsg = false
    },
    beforeCloseMsg() {
      this.dialogFormMsg.verificationCode = ''
      this.$refs['dialogFormMsg'].clearValidate()
      this.dialogVisibleMsg = false
    },
    // 校验短信验证码
    validateMessage(rule, value, callback) {
      let expReg = /^\d{6}$/
      if (!expReg.test(value)) {
        callback(new Error(this.$t('scoreEntryMana.validateMessage')))
      } else {
        callback()
      }
    },
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    reset() {
      for (let key in this.queryForm.condition) {
        if (key !== 'calendarId') {
          this.queryForm.condition[key] = ''
        }
      }
      this.queryForm.condition.calendarId = this.$refs.semester.$data.currentTermId
      this.onSubmit()
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    getListData() {
      scoreManagementApi.getStudentGradeMaintain(this.queryForm).then((res) => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total
      })
    },
    calendarIdLoadDone() {
      this.onSubmit()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    },
    // 返回主页
    refreshMainPage() {
      this.multipleSelection = []
      this.indexKey = 0
      this.onSubmit()
    },
    // 课程代码、名称搜索方法
    remoteMethod(val) {
      if (val !== '') {
        this.loading = true
        let lang = this.$store.getters.language
        scoreManagementApi.queryCourseInfoByCourseCode({
          courseCode: val
        }).then(res => {
          this.loading = false
          if (res.code == 200) {
            const list = res.data &&
              res.data.map(e => {
                let obj = {}
                obj.label = lang === 'cn' ? e.name + '(' + e.code + ')' : e.nameEn + '(' + e.code + ')'
                obj.value = e.code
                return obj
              })
            this.options.courseCodeList = list
          }
        })
      } else {
        this.options.courseCodeList = []
        this.queryForm.condition.courseCodeAndName = ''
      }
    },
    // 获取课程类别
    getCourseType() {
      coursesLabelList().then(res => {
        res.data.forEach(item => {
          this.options.courseType.push({
            label: item.label,
            value: item.id,
            key: item.id
          })
        })
      })
    },
    // 删除成绩
    deleteScore() {
      if (this.multipleSelection.length > 0) {
        this.operationStatus = 'del'
        scoreManagementApi.sendMessage({
          "pushType": 2,
          "type": 1
          }).then(res => {
            if (res.code === 200) {
              this.dialogVisibleMsg = true
              this.titleMsg = this.$t('scoreEntryMana.messageValidate')
              this.messageInfo = res.data
              this.passwordNum = res.data.id
            }
        })
        // let deleteArray = this.multipleSelection.map(value => {
        //   return value.id
        // })
        // this.title = this.$t('scoreMangementBase.deleteGrade')
        // this.dialogVisible = true
      } else {
        this.$message(this.$t('scoreMangementBase.pleaseChoose'))
      }
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        scoreManagementApi.downloadOne(key).then(res => {
          this.exportResult = res.data
          if (res.code == 200 && res.data.status) {
            this.exportButton = false
            let path = `${baseUrl}/minorScoreExport/file?path=` + res.data.path + '&name=' + name
            window.location.href = path
            this.$message.success(this.$t('result.exportSuccessfully'))
            this.$refs.downloadRef.close()
          } else {
            this.delayRequest(key, name)
          }
        })
      }, 3000)
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        scoreManagementApi.downloadOne(key, name).then(res => {
          this.exportResult = res.data
          if (res.code == 200 && res.data.status) {
            this.exportButton = false
            let path = `${baseUrl}/minorScoreExport/file?path=` + res.data.path + '&name=' + name
            window.location.href = path
            this.$message.success(this.$t('result.exportSuccessfully'))
            this.$refs.downloadRef.close()
          } else {
            this.delayRequest(key, name)
          }
        })
      }, 3000)
    },
    // 导出
    exportScore() {
      if (this.dataList.length === 0) {
        this.$message.error(this.$t('externamExchangeBase.exportNoData'))
        return
      }
      let idList = []
      if (this.multipleSelection.length > 0) {
        idList = this.multipleSelection.map(value => {
          return value.id
        })
      }
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      this.exportResult = null
      this.$refs.downloadRef.open()
      this.exportButton = true
      setTimeout(() => {
        scoreManagementApi.downloadStudentGradeMaintain({
          "calendarId": this.queryForm.condition.calendarId,
          "course": this.queryForm.condition.course,
          "studentIdOrName": this.queryForm.condition.studentIdOrName,
          "selectRowIds": idList
        }).then(res => {
          if (res.success) {
            this.normalDelayRequest(res.key, res.msg)
          }
        }).catch(e => {
          this.$refs.downloadRef.close()
          this.exportButton = false
        })
      }, 3000)
    },
    // 查看学生基本信息
    selectStudentInfo(row) {
      this.detailInfo = {
        studentCode: row.studentId,
        projectId: this.userInfo.currentManageDptId
      }
      this.indexKey = 1
    },
    // 查看
    selectInfo(row) {
      this.detailInfo = {
        id: row.id
      }
      this.indexKey = 2
    },
    // 修改
    editInfo(row) {
      this.operationStatus = 'edit'
      this.detailInfo = {
        id: row.id
      }
      // this.indexKey = 3 
      scoreManagementApi.sendMessage({
        "pushType": 1,
        "type": 1
        }).then(res => {
          if (res.code === 200) {
            this.dialogVisibleMsg = true
            this.titleMsg = this.$t('scoreEntryMana.messageValidate')
            this.messageInfo = res.data
            this.passwordNum = res.data.id
          }
      })
      // this.detailInfo = {
      //   id : row.id
      // }
      // this.indexKey = 3
    },
    // 关闭前回调
    beforeClose() {
      this.cancel()
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      Object.keys(this.dialogForm).forEach(key => this.dialogForm[key] = '')
      this.$refs['dialogForm'].clearValidate()
    },
    // 确定
    confirm() {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          let deleteArray = this.multipleSelection.map(value => {
            return value.id
          })
          scoreManagementApi.deleteStudentGradeMaintain({
            "idList": deleteArray,
            "scoreChangeReason": this.dialogForm.deleteReason
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success', 
                message: this.$t('scoreMangementBase.deleteSuccessfully')
              })
              this.cancel()
              this.onSubmit()
            }
          })
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .score-change-apply-container ::v-deep {
    .div-main {
      margin-bottom: 16px;
    }
  }
</style>